package com.example.ccj.b.c.form;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import com.example.ccj.R;
import com.example.ccj.b.c.draw.TopBar;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.ToastUtils;

import java.lang.reflect.Field;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 加载表单数据view
 * @author 驰珺
 * whechat   : chijun9
 * create at : 2024/7/1 13:28
 */
public class LoadFormDataView extends LinearLayout {
    private static final String TAG = "表单数据加载";
    LinearLayout fieldContent;

    TopBar topBar;

    FormDataFormatter formDataFormatter;


    public LoadFormDataView(Context context) {
        super(context);
        initView(context);
    }

    public LoadFormDataView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private void initView(Context context){
        LinearLayout.inflate(context, R.layout.view_load_data_form,this);
        topBar = findViewById(R.id.view_load_data_form_top);
        fieldContent = findViewById(R.id.view_load_data_form_content);
        topBar.getTopTitle().setGravity(Gravity.CENTER_VERTICAL);
        setOrientation(VERTICAL);
    }


    public <T> void setObject(T obj, Class<T> tClass, FormDataFormatter formDataFormatter){
        this.formDataFormatter = formDataFormatter;
        jxConfig(tClass,obj);
    }

    public void setMTitleName(String titleName){
        if (titleName != null) this.post(() -> topBar.setTitle(titleName));
    }

    private void jxConfig(Class<?> mClass,Object obj){
        Observable.create((ObservableOnSubscribe<ShowDataFieldView>) e -> {
                    Field[] fields = mClass.getDeclaredFields();
                    for (Field field : fields) {
                        ShowDataFieldView dataFieldView = new ShowDataFieldView(getContext());
                        DataConfig dataConfig = new DataConfig();
                        field.setAccessible(true);
                        MFormDataField dataField = field.getAnnotation(MFormDataField.class);
                        //字段的属性配置
                        if (dataField != null) {
                            dataConfig.setDataName(field.getName());
                            dataConfig.setHint(dataField.hint());
                            dataConfig.setFieldName(dataField.value());
                            dataConfig.setOrder(dataField.order());
                            dataConfig.setType(dataField.type());
                            dataConfig.setFormDataFormatter(formDataFormatter);

                            //字段的值
                            if (obj != null) {
                                String value = String.valueOf(field.get(obj));
                                LogUtils.d("获取值: " + field.getName()+":" + value);
                                if (!StringUtils.isEmpty(value)) dataConfig.setText(value);
                            }
                            dataFieldView.setDataConfig(dataConfig);
                        } else {
                            continue;
                        }
                        e.onNext(dataFieldView);
                    }
                    e.onComplete();
                }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ShowDataFieldView>() {
                    @Override
                    public void onSubscribe(Disposable d) {}
                    @Override
                    public void onNext(ShowDataFieldView inPutData) {
                        fieldContent.addView(inPutData);
                    }
                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e(TAG,"加载表单失败: ",e );
                        ToastUtils.showShort("加载表单失败：",e.getMessage());
                    }
                    @Override
                    public void onComplete() {
                        LogUtils.d(TAG,"加载表单成功");
                        sort();
                    }
                });

    }

    /**
     * 排序字段
     */
    public void sort(){
        int n = fieldContent.getChildCount();
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i; j++) {
                View childAt1 = fieldContent.getChildAt(j);
                View childAt2 = fieldContent.getChildAt(j + 1);
                if (childAt1 instanceof ShowDataFieldView && childAt2 instanceof ShowDataFieldView) {
                    int orderA = ((ShowDataFieldView) childAt1).dataConfig.order;
                    int orderB = ((ShowDataFieldView) childAt2).dataConfig.order;
                    if (orderA > orderB) {
                        View childAt = fieldContent.getChildAt(j);
                        fieldContent.removeViewAt(j);
                        fieldContent.addView(childAt,j+1);
                    }
                }
            }
        }
    }


}
